import React, { useState, useRef, useEffect } from 'react'
import { Button, Form, Modal, Col, Input, Space, Table, Tag, message } from 'antd'
import { DownOutlined, PlusOutlined, ExclamationCircleOutlined, RightOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { addParamsAPI, editParamsAPI, delParamsAPI } from '../../../app/params'

const { confirm } = Modal
export default function ParsmaTab(props) {
    // console.log(props)
    const { paramsList, btnDisable, getParamsList, catId, attrSel } = props
    // 增加参数form表单实例
    const [addParamsForm] = Form.useForm()
    // 编辑参数form表单实例
    const [editParamsForm] = Form.useForm()
    // 拿到Input框的dom
    const inpRef = useRef()
    // 是否显示Input框
    const [isVisibleInp, setIsVisibleInp] = useState(false)
    // 是否显示添加参数模态框
    const [isAddParamsVisible, setIsAddParamsVisible] = useState(false)
    // 是否显示编辑参数模态框
    const [isEditParamsVisible, setIsEditParamsVisible] = useState(false)
    // 按钮加载中
    const [btnLoading, setBtnLoading] = useState(false)
    // 控制Input框显示
    useEffect(() => {
        inpRef.current?.focus()
    }, [isVisibleInp])

    // 增加参数校验规则
    const addParamsRules = {
        attr_name: [
            {
                required: true, message: '请输入参数名称'
            },
            {
                min: 2, max: 7, message: '长度要求在2~7个字符'
            }
        ]
    }
    // 添加参数
    const addParams = () => {
        addParamsForm.resetFields()
        setIsAddParamsVisible(true)
    }
    // 处理确认增加参数
    const handleAddParams = () => {
        addParamsForm.validateFields()
        .then(async values => {
            setBtnLoading(true)
            const { meta } = await addParamsAPI(catId, {
                ...values,
                attr_sel: attrSel
            })
            if(meta.status !== 201) {
                setBtnLoading(false)
                return message.error('添加参数失败')
            }
            setBtnLoading(false)
            setIsAddParamsVisible(false)
            getParamsList(catId, attrSel)
        })
        .catch(() => {
            // setBtnLoading(false)
            message.error('请按规范填写内容')
        })
    }
    // 处理取消添加参数
    const handleCancelAddParams = () => {
        setIsAddParamsVisible(false)
    }

    // 编辑参数
    const onEditParams = (record) => {
        editParamsForm.resetFields()
        setIsEditParamsVisible(true)
        const { attr_name } = record
        editParamsForm.setFieldsValue({attr_name})
    }
    // 处理确认增加参数
    const handleEditParams = () => {
        editParamsForm.validateFields()
        .then(async values => {
            setBtnLoading(true)
            const { cat_id, attr_sel, attr_id } = paramsList[0]
            const { meta } = await editParamsAPI(cat_id, attr_id, {
                ...values,
                attr_sel
            })
            if(meta.status !== 200) {
                setBtnLoading(false)
                return message.error('添加参数失败')
            }
            setBtnLoading(false)
            setIsEditParamsVisible(false)
            getParamsList(catId, attrSel)
        })
        .catch(() => {
            message.error('请按规范填写内容')
        })
    }
    // 处理取消添加参数
    const handleCancelEditParams = () => {
        setIsEditParamsVisible(false)
    }

    // 删除参数
    const onDeleteParams = ({cat_id, attr_id}) => {
        confirm({
            title: '该操作将永久删除该参数，是否继续？',
            icon: <ExclamationCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            async onOk() {
              const { meta } = await delParamsAPI(cat_id, attr_id)
              if(meta.status !== 200) return message.error('删除该参数失败')
              message.success('删除该参数成功')
              getParamsList(catId, attrSel)
            }
          })
    }

    // 增加标签
    const addTag = () => {
        setIsVisibleInp(true)
    }
    // Input框确认和失去焦点
    const inputConfirm = async (e, {cat_id, attr_name, attr_id, attr_vals, attr_sel}) => {

        const newVals = `${attr_vals} ${e.target.value}`
        console.log(newVals)
        if(!newVals.trim()) {
            setIsVisibleInp(false)
            return
        }
        const { meta } = await editParamsAPI(cat_id, attr_id, {
            attr_name,
            attr_sel,
            attr_vals: newVals
        })
        if(meta.status !== 200) return message.error('添加参数属性失败')
        getParamsList(catId, attrSel)
        setIsVisibleInp(false)
    }
    // 关闭标签
    const closeTag = async (index, newValsArr, {cat_id, attr_name, attr_id, attr_sel}) => {
        // console.log(index)
        newValsArr.splice(index, 1)
        console.log(newValsArr)
        const { meta } = await editParamsAPI(cat_id, attr_id, {
            attr_name,
            attr_sel,
            attr_vals: newValsArr.join(',')
        })
        if(meta.status !== 200) return message.error('删除参数属性失败')
        getParamsList(catId, attrSel)
    }

    // table表格展开的渲染内容
    const expandedRowRender = (record) => {
        const newValsArr = record.attr_vals.trim().split(' ')
        const component = <Col>
            {
                record.attr_vals && newValsArr.map((item, index) => {
                    return  <Tag
                        key={index}
                        closable
                        color="processing"
                        onClose={e => {
                                e.preventDefault()
                                closeTag(index, newValsArr, record)
                                }}
                            >
                            {item}
                    </Tag>
                })
            }
            {isVisibleInp ? <Input
                ref={inpRef}
                size="small"
                onBlur={e => inputConfirm(e, record )}
                onPressEnter={e => inputConfirm(e, record )}
                style={{
                    width: '78px',
                    marginRight: '8px',
                    verticalAlign: 'top'
                }}
                            /> :
             <Tag
                 onClick={() => addTag()}
             >
                <PlusOutlined /> New Tag
             </Tag>
            }
        </Col>
        return component
    }
     // 展开图标自定义配置
     const expandIcon = ({ expanded, onExpand, record }) => {
        const component =  expanded ? (<DownOutlined onClick={e => onExpand(record, e)} />) : (<RightOutlined onClick={e => onExpand(record, e)} />)
        return component
    }
    // table表格每列的标题
    const paramsColumns = [
        {
            title: '#',
            dataIndex: 'index',
            width:'100px'
        },
        {
            title: '参数名称',
            dataIndex: 'attr_name'
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => {
                const component = <Space>
                <Button onClick={() => onEditParams(record)} icon={<EditOutlined />} type="primary">编辑</Button>
                <Button onClick={() => onDeleteParams(record)} icon={<DeleteOutlined />} type="danger">删除</Button>
            </Space>
            return component
            }
        }
    ]
    return (
        <>
            <Button onClick={addParams} disabled={btnDisable} style={{marginBottom: '20px'}} type="primary">添加{attrSel === 'many' ? '参数' : '属性'}</Button>
            {/* 参数表格 */}
            <Table
                bordered
                dataSource={paramsList.length && paramsList}
                columns={paramsColumns}
                pagination={false}
                scroll={{y: '480px'}}
                expandable={{
                        expandedRowRender,
                        expandIcon
                    }}
                rowKey={record => record.attr_id}
            />
            {/* 添加参数模态框 */}
            <Modal
                cancelText="取消"
                okText="确认"
                title={attrSel === 'many' ? '添加动态参数' : '添加静态属性'}
                visible={isAddParamsVisible}
                onOk={handleAddParams}
                onCancel={handleCancelAddParams}
                confirmLoading={btnLoading}
            >
            <Form
                name="addrole"
                form={addParamsForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    label={attrSel === 'many' ? '动态参数' : '静态属性'}
                    name="attr_name"
                    rules={addParamsRules.attr_name}
                >
                    <Input />
                </Form.Item>
            </Form>
            </Modal>
             {/* 编辑参数模态框 */}
            <Modal
                cancelText="取消"
                okText="确认"
                title={attrSel === 'many' ? '编辑动态参数' : '编辑静态属性'}
                visible={isEditParamsVisible}
                onOk={handleEditParams}
                onCancel={handleCancelEditParams}
                confirmLoading={btnLoading}
            >
            <Form
                name="editrole"
                form={editParamsForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    label={attrSel === 'many' ? '动态参数' : '静态属性'}
                    name="attr_name"
                    rules={addParamsRules.attr_name}
                >
                    <Input />
                </Form.Item>
            </Form>
            </Modal>
        </>
    )
}